<template>
  <div class="width-100-per height-100-per">
    <div class="layout-right-center width-100-per margin-bottom-10-px">
      <div class="layout-side margin-right-10-px">
        <span class="margin-right-5-px">标题</span>
        <a-input class="formInput margin-right-5-px" ></a-input>
      </div>
      <div class="layout-side margin-right-10-px">
        <span class="margin-right-5-px">时间</span>
        <a-range-picker style="width: 250px" @change="onChangeTime" />
      </div>
      <a-button-group>
        <a-button icon="search" @click="selectRepaired">查询</a-button>
        <a-button icon="reload" @click="removeRepaired">清空</a-button>
      </a-button-group>
    </div>
    <div class="width-100-per">

      <!--    :rowSelection="rowSelection"-->
      <a-table
        :locale="{emptyText:'暂无数据'}"
        :rowKey="record => record.key"
        :columns="columns"
        :dataSource="repairedData"
        :pagination="paginationUser"
      >
      <span slot="tags" slot-scope="tags">
        <a-tag v-for="tag in tags" color="blue" :key="tag">{{tag}}</a-tag>
      </span>
        <span slot="action" slot-scope="text, record">
          <a @click="onViewClick(record.key)">详情</a>
          <template v-if="userType === '1'||userType === '2'">
            <a-divider type="vertical"/>
            <a @click="onEditClick(record.key)">编辑</a>
          </template>
          <template v-if="userType === '2'">
            <a-divider type="vertical"/>
            <a-popconfirm title="确定删除该条数据吗？" placement="topRight" @confirm="onDeleteClick(record.key)">
              <a @click="">删除</a>
            </a-popconfirm>
          </template>
      </span>
      </a-table>
    </div>
    <a-modal
      :title="modalTitle"
      width="848px"
      :visible="modalPersonnel"
      @cancel="cancelPersonnel">
      <template slot="footer">
        <a-button v-if="!addRepair" key="submit" type="primary" :loading="loading" @click="okPersonnel">确认</a-button>
        <a-button v-if="current === 1" key="back" icon="reload" @click="handleReset">重置</a-button>
        <a-button v-if="current>0" key="prev" icon="left" style="margin-left: 8px" @click="addPrev">上一步</a-button>
        <a-button v-if="current<2 && addRepair" icon="right" type="primary" @click="addNext">继续</a-button>
        <a-button v-if="current ===2" key="add" icon="check" type="primary" @click="handleOkGoon">提交</a-button>
      </template>
      <a-steps v-if="addRepair" :current="current">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" />
      </a-steps>
      <div v-if="!addRepair || current===0" class="layout-left-top padding-10-px overflow-auto" style="width: 800px;height: 500px">
        <div class="layout-left-top" style="width: 350px;">
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">具体楼栋</div>
            <a-input :disabled="disabled" class="formInput" v-model="repairData.repCode"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">报修人员</div>
            <a-input :disabled="disabled" class="formInput" v-model="repairData.repStarId"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">报修区域</div>
            <a-select :disabled="disabled" placeholder="" class="formInput"  v-model="repairData.loctionId">
              <a-select-option value="999">请选择</a-select-option>
              <a-select-option v-for="(i,index) in repLocationData" :value="i.key" :key="index">{{i.title}}</a-select-option>
            </a-select>
          </div>
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">报修类别</div>
            <a-select :disabled="disabled" placeholder="" class="formInput"  v-model="repairData.repTypeId">
              <a-select-option value="999">请选择</a-select-option>
              <a-select-option v-for="(i,index) in repTypeIdData" :value="i.key" :key="index">{{i.title}}</a-select-option>
            </a-select>
          </div>
        </div>
        <div class="layout-left-top" style="width: 400px">
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">联系电话</div>
            <a-input :disabled="disabled" class="formInput" v-model="repairData.repStarIdP"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">报修时间</div>
            <a-input :disabled="disabled" class="formInput" v-model="repairData.repStatTime"></a-input>
          </div>
          <div class="layout-left-top margin-bottom-10-px margin-top-10-px">
            <div class="formSpan">报修备注</div>
            <a-textarea :disabled="disabled" class="" style="width: 321px" placeholder="报修备注" :rows="3" v-model="repairData.repRemarkStar"/>
          </div>
        </div>
        <div class="layout-left-top margin-bottom-10-px margin-top-10-px">
          <div class="formSpan">报修图片</div>
          <div :disabled="disabled" style="width: 690px;height: 400px;overflow: auto;border: 1px solid rgb(217, 217, 217)" class="layout-left-top">
            <img v-for="(i,index) in repairData.repImgStar" :key="index" class="imgS" :src="i"/>
          </div>
        </div>
      </div>
      <div v-if="current === 1 && addRepair" class="width-100-per overflow-auto padding-10-px" style="height: 500px">
        <div class="layout-left-top margin-bottom-10-px margin-top-10-px">
          <div class="formSpan">维修材料</div>
          <div class="layout-center padding-10-px" style="width: calc(100% - 140px);border: 1px solid rgb(217, 217, 217);margin-bottom: 9px;">
            <div style="max-height: 200px" class="overflow-auto width-100-per">
              <div class="layout-left-top width-100-per margin-bottom-10-px" v-for="(i,index) in repairDataed.materials" :key="index">
                <span style="margin-right: 20px;width:50px; ">材料{{index++}}</span>
                <div class="layout-side margin-top-10-px margin-bottom-10-px">
                  <span class="formSpan">材料名称:</span>
                  <a-tree-select
                    class="formInput"
                    :value="materialValue"
                    :treeData="materialDatas"
                    treeDefaultExpandAll
                    @select="onSelect"
                    v-model="i.matId"
                  >
                  </a-tree-select>
                </div>
                <div class="layout-side margin-top-10-px margin-bottom-10-px">
                  <span class="formSpan">数量:</span>
                  <a-input class="formInput" v-model="i.matRecordNum"></a-input>
                </div>
                <a-icon v-if="repairDataed.materials.length>1" type="close" title="删除该材料" @click="deleteMat(index)" style="margin-top: 20px;margin-left: 10px;"/>
              </div>
            </div>
            <a-button class="margin-top-10-px" icon="plus" title="添加材料" @click="addMat">添加</a-button>
          </div>
        </div>
        <div class="layout-left-center" style="margin-bottom: 20px;">
          <span class="formSpan">完工时间</span>
          <a-date-picker class="formInput" @change="onChangeData" :value="showDataTime"/>
        </div>
        <div class="layout-left-top" style="margin-bottom: 20px;">
          <span class="formSpan">完工备注</span>
          <a-textarea style="width: 321px" placeholder="完工备注" :rows="6" v-model="repairDataed.repRemarkEnd"/>
        </div>
        <div class="layout-left-top " style="margin-bottom: 20px;">
          <span class="formSpan">完工图片</span>
          <div style="width: 700px;height: 400px;overflow: auto;border: 1px solid rgb(217, 217, 217)" class="layout-left-top">
            <!--              <div class="addM layout-center bg-color-white border"><a-icon type="plus" title="添加" style="font-size: 80px;color: #DDDDDD"/></div>-->
            <!--              <img v-for="(i,index) in repairData.repImgStar" :key="index" class="imgS" :src="i"/>-->
            <!--              image/jpg,image/jpeg,image/png-->

            <div class="clearfix layout-left-top padding-10-px">
              <a-upload
                accept="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                listType="picture-card"
                :fileList="fileList"
                @preview="handlePreview"
                @change="handleChange"

              >
                <div>
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </div>
          </div>
        </div>
      </div>
      <div v-if="current === 2 && addRepair" class="width-100-per layout-center padding-10-px" style="height: 500px">
        <div class="layout-side">
          <a-icon type="loading" :style="{ fontSize: '40px', color: '#52c41a' }"/>
          <span>点击提交，新增数据！！！</span>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import {Button, DatePicker, Divider, Icon, Input, Modal, Popconfirm, Select, Steps, Table, Tag, TreeSelect, Upload} from 'ant-design-vue'
  import moment from 'moment'
  import {indexConfig} from './IndexConfig'
  import {pagination} from "../../lib/utils";

  export default {
    name: "UnRepair",
    components: {
      AUpload:Upload,
      aTreeSelect:TreeSelect,
      ADatePicker:DatePicker,
      ASelect:Select,
      ASelectOption:Select.Option,
      ARangePicker:DatePicker.RangePicker,
      ATable: Table,
      ATag: Tag,
      ADivider: Divider,
      AIcon: Icon,
      AButton: Button,
      AButtonGroup: Button.Group,
      AInput:Input,
      APopconfirm:Popconfirm,
      AModal:Modal,
      ATextarea:Input.TextArea,
      ASteps:Steps,
      AStep:Steps.Step,
    },
    data(){
      return{
        repairID:'',
        userID:'',
        repStarIds:'',
        userType:'0',
        imgNum:0,
        data:[],
        /****上传**********************/
        previewVisible: false,
        previewImage: '',
        fileList: [],
        /****上传*********************/
        materialValue:'请选择',
        materialDatas:[],
        modalTitle:'',
        addRepair:true,
        current:0,
        footers:this.slot,
        visible:false,
        disabled:true,
        repairData:{
          repCode:'',
          repStarId:'',
          repStarIdP:'',
          // repImgStar:[],
          repImgStar:["",
            ""],
          repStatTime:'',
          repRemarkStar:'',
          repTypeId:1,
          loctionId:1
        },
        repairDataed:{
          materials:[
            { matId:'请选择',matRecordNum:'1',}
          ],
          repEndTime:moment().format('YYYY-MM-DD'),
          repRemarkEnd:'',
          repEndId:'',
          repImgEnd:[],
        },
        steps:indexConfig.steps,
        repLocationData:indexConfig.repLocationData,
        repTypeIdData:indexConfig.repTypeIdData,
        columns:indexConfig.columns01,
        repairedData:[],
        loading:false,
        modalPersonnel:false,
        paginationUser:pagination(this.changePage,this.showSizeChange),
      }
    },
    computed:{
      showDataTime(e){
        return moment(this.repairDataed.repEndTime === ""?new Date():this.repairDataed.repEndTime,"YYYY-MM-DD")
      }
    },
    mounted(){
      this.userType = JSON.parse(this.$store.getters.currentUser).type;
      this.userID=JSON.parse(this.$store.getters.currentUser).id;
      this.showTable()
      this.showMaterialTreeData()
      console.log('2')
    },
    methods:{
      //材料树
      showMaterialTreeData(){
        const that = this;
        let AllMaterialTypes=[];
        let AllMaterials=[];
        that.$apollo.query({
          query:require('../../graphql/material/query/findAllMaterialType.gql'),
          variables:{},
          fetchPolicy:'no-cache'
        }).then(data=>{
          const findAllMaterialType = data.data.findAllMaterialType;
          for(let i in findAllMaterialType){
            AllMaterialTypes.push({
              key:findAllMaterialType[i].id,
              title:findAllMaterialType[i].matTypeName,
              parentId:findAllMaterialType[i].matTypeParentId,
              disabled:true
            })
          }
          that.$apollo.query({
            query: require('../../graphql/material/query/findAllMaterial.gql'),
            variables: {},
            fetchPolicy: 'no-cache'
          }).then(datas => {
            const findAllMaterial=datas.data.findAllMaterial;
            for(let j in findAllMaterial){
              AllMaterials.push({
                key:findAllMaterial[j].id,
                title:findAllMaterial[j].matName,
                parentId:findAllMaterial[j].matParengId,
                disabled:false
              })
            }
            const treeR = AllMaterialTypes.concat(AllMaterials);
            that.showMaterialTrees(treeR);
          }).catch(error=>{
            console.log(error)
          })
        }).catch(error=>{
          console.log(error)
        })
      },
      //组装材料树
      showMaterialTrees(tree){
        const that = this;
        const newTree = [];
        for (let r of tree) {
          if (r.parentId === '999') {
            let ct = that.dataTreeDg(r, tree);
            if (ct.length !== 0) {
              newTree.push({
                title: r.title,
                key: r.key,
                value:r.key,
                disabled:r.disabled,
                children: that.dataTreeDg(r, tree)
              })
            } else {
              newTree.push({
                title: r.title,
                key: r.key,
                value:r.key,
                disabled:r.disabled,
              })
            }
          }
        }
        that.materialDatas=[{
          title: '材料总览',
          key: '999',
          value:'999',
          disabled:true,
          children:newTree
        }]
      },
      //树组装
      dataTreeDg(pt, tree) {
        const that = this;
        let newRR = [];
        for (let t of tree) {
          if (pt.key === t.parentId) {
            let ct = that.dataTreeDg(t, tree);
            if (ct.length !== 0) {
              newRR.push({
                title: t.title,
                key: t.key,
                value:t.key,
                disabled:t.disabled,
                children: ct,
              });
            } else {
              newRR.push({
                title: t.title,
                key: t.key,
                value:t.key,
                disabled:t.disabled,
              });
            }
          }
        }
        return newRR;
      },
      //初始加载表格
      showTable(){
        const that = this;
        that.repairedData = [];
        that.$apollo.query({
          query:require('../../graphql/repair/query/findAllByRepState.gql'),
          variables:{repState:"1"},
          fetchPolicy:'no-cache'
        }).then(data=>{
          const findAllByRepState = data.data.findAllByRepState;
          for(let i in findAllByRepState){
            const repTypes=[];
            const loctions = [];
            for(let j in that.repTypeIdData){
              if(findAllByRepState[i].repTypeId === that.repTypeIdData[j].key){
                repTypes.push(that.repTypeIdData[j].title);
              }
            }
            for(let j in that.repLocationData){
              if(findAllByRepState[i].loctionId === that.repLocationData[j].key){
                loctions.push(that.repLocationData[j].title);
              }
            }
            that.repairedData.push({
              key:findAllByRepState[i].id,
              title:findAllByRepState[i].repCode,
              repTypeId:repTypes[0],
              loctionId:loctions,
              repStatTime:findAllByRepState[i].repStatTime,
            })
          }

        }).catch((error)=>{
          console.log(error);
        })
      },
      /**上传图片*/
      handleCancel() {
        this.previewVisible = false;
      },
      handlePreview(file) {
        this.previewImage = file.url || file.thumbUrl;
        this.previewVisible = true;
      },
      handleChange({ fileList }) {
        for(let i in fileList){
          fileList[i].status = 'done';
        }
        this.fileList = fileList;
        if(this.imgNum === 2){
          this.repairDataed.repImgEnd.push(
            fileList[fileList.length-1].thumbUrl
          )
          this.imgNum = 0;
          console.log(this.repairDataed.repImgEnd)
          return
        }
        this.imgNum++;
      },
      /*上传图片*/
      //删除材料
      deleteMat(e){
        let a = e--;
        this.repairDataed.materials.splice(a,1);
      },
      //材料新增
      addMat(){
        this.repairDataed.materials.push(
          { matId:'请选择',matRecordNum:'1',}
        )
      },
      //材料选择
      onSelect(value,node){
        this.materialValue = value
      },
      //日期
      onChangeData(date, dateString){
        console.log(date, dateString);
        this.repairDataed.repEndTime = dateString;
      },
      //继续
      addNext(){
        this.current++
      },
      //上一步
      addPrev(){
        this.current--
      },
      //重置
      handleReset(){
        console.log('重置')
        this.repairDataed={
          materials:[
            { matId:'请选择',matRecordNum:'1',}
          ],
            repEndTime:moment().format('YYYY-MM-DD'),
            repRemarkEnd:'',
            repEndId:'',
            repImgEnd:[],
        };
        this.fileList = [];
      },
      handleCancelGoon(){

        this.visible=false;
      },
      //维修编辑
      handleOkGoon(){
        console.log(this.repairData)
        console.log(this.repairDataed)

        const that = this;
        const mater = [];
        for(let k in that.repairDataed.materials){
          mater.push({
            matId:that.repairDataed.materials[k].matId,
            matRecordNum:that.repairDataed.materials[k].matRecordNum
          })
        }
        console.log(that.repairID)
        const newRepaired = {
            id:that.repairID,
            loctionId:that.repairData.loctionId,
            materialRecordId:mater,
            repCode:that.repairData.repCode,
            // repEndId:that.userID,
            repEndId:that.userID,
            repEndTime:that.repairDataed.repEndTime,
            repImgEnd:"",
            repImgStar:"",
            // repRemarkEnd:that.repairDataed.repRemarkEnd,
            repRemarkEnd:"",
            repRemarkStar:that.repairData.repRemarkStar,
            repStarId:that.repStarIds,
            repStarIdP:that.repairData.repStarIdP,
            repStatTime:that.repairData.repStatTime,
            repState:"2",
            repTypeId:that.repairData.repTypeId,
            message:'',
          }
        that.$apollo.mutate({
          mutation:require('../../graphql/repair/mutation/saveRepair.gql'),
          variables:{entity:newRepaired},
        }).then((data)=>{
          console.log(data)
          that.$message.success('维修成功');
          this.modalPersonnel = false;
          this.current = 0;
        }).catch(error=>{

          that.$message.error('维修失败');
          console.log(error);
        })
      },
      //人员弹框确认按钮
      okPersonnel(e) {
        this.loading = true;
        setTimeout(() => {
          this.modalPersonnel = false;
          this.loading = false;
        }, 200);
      },
      //人员弹框右上角X按钮
      cancelPersonnel(e) {
        this.modalPersonnel = false;
        this.current = 0;
      },

      findStarID(id){
        const that = this;
        that.$apollo.query({
          query:require('../../graphql/repair/query/findRepairById.gql'),
          variables:{id},
          fetchPolicy:'no-cache'
        }).then(data=>{
          const findRepairById=data.data.findRepairById;
          console.log(findRepairById)
          this.$apollo.query({
            query:require('../../graphql/army/query/findUserById.gql'),
            variables:{id:findRepairById.repStarId},
            fetchPolicy:'no-cache'
          }).then((datas)=>{
            const findUserById = datas.data.findUserById;
            that.repairData={
              repCode:findRepairById.repCode,
              repStarId:findUserById.name,
              repStarIdP:findRepairById.repStarIdP,
              // repImgStar:findRepairById.repImgStar,
              repImgStar:["",
                "",
                ""],

              repStatTime:findRepairById.repStatTime,
              repRemarkStar:findRepairById.repRemarkStar,
              repTypeId:findRepairById.repTypeId,
              loctionId:findRepairById.loctionId
            };
            that.repStarIds = findRepairById.repStarId;
          }).catch((error)=>{
            console.log(error)
          })
        }).catch(error=>{
          console.log(error)
        })
      },
      onViewClick(id) {
        const that = this;
        that.findStarID(id);
        that.modalTitle = '报修详情';
        that.addRepair = false;
        that.modalPersonnel = true;
      },
      //编辑
      onEditClick(id) {
        const that = this;
        that.findStarID(id);
        that.repairID = id;
        that.modalTitle = '维修编辑';
        that.addRepair = true;
        that.modalPersonnel = true;
      },
      onDeleteClick(id) {
        this.$apollo.mutate({
          mutation:require('../../graphql/repair/mutation/deleteRepairById.gql'),
          variables:{id:id}
        }).then((data)=>{
          this.showTable();
          this.$message.success("删除成功！")
        }).catch((error)=>{
          console.log(error)
        })
      },
      //选择每页多少条后回调
      showSizeChange(current,pageSize){
        this.changePage(current,pageSize)
      },
      //点击页码回调
      changePage(current,pageSize){
        const that = this;
        that.paginationUser.defaultPageSize = pageSize;
        that.paginationUser.current = current;
      },
      //时间
      onChangeTime(date, dateString) {
        console.log(date, dateString);
      },
      //查询
      selectRepaired(){
        console.log('查询');
      },
      //清空
      removeRepaired(){
        console.log('清空');
      },
    }
  }
</script>

<style scoped>
  .imgS{
    width: 200px;
    height: 200px;
    background: #1890FF;
    margin: 10px
  }
  .addM{
    width: 200px;
    height: 200px;
    margin: 10px
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

</style>

